package com.example.administrator.bluetooth_data_transmission;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.administrator.bluetooth_data_transmission.adapter.LeDeviceListAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleDevice;
import cn.com.heaton.blelibrary.ble.callback.BleConnCallback;
import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;

public class BlueToothListActivity extends BaseActivity {

    private String TAG = BlueToothListActivity.class.getSimpleName();

    private ImageView ivBack;
    private ListView rvList;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private Ble<BleDevice> mBle;
    private List<String> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth_list);
        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        rvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BleDevice device = mLeDeviceListAdapter.getDevice(position);
                if (device == null) return;
                if (mBle.isScanning()) {
                    mBle.stopScan();
                }
                if (device.isConnected()) {
                    mBle.disconnect(device);
                } else if (!device.isConnectting()) {
//            mBle.connect(device, connectCallback); //也可以
                    mBle.connect(device, connectCallback);//新添加通过mac地址进行连接
                }
            }
        });
    }

    private void initViews() {
        ivBack = findViewById(R.id.iv_back);
        rvList = findViewById(R.id.rv_list);
        mLeDeviceListAdapter = new LeDeviceListAdapter(this);
        rvList.setAdapter(mLeDeviceListAdapter);
        mBle = Ble.getInstance();
        checkBle();//检测蓝牙是否支持BLE以及是否打开
    }

    //检查蓝牙是否支持及打开
    private void checkBle() {
        // 检查设备是否支持BLE4.0
        if (!mBle.isSupportBle(this)) {
            finish();
            return;
        }
        if (!mBle.isBleEnable()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, Ble.REQUEST_ENABLE_BT);
        }else {
            //请求权限
            requestPermission();
        }
    }

    //请求权限
    private void requestPermission(){
        requestPermission(new String[]{Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.ACCESS_COARSE_LOCATION},
                "请求蓝牙相关权限", new GrantedResult() {
                    @Override
                    public void onResult(boolean granted) {
                        if (granted) {
                            //初始化蓝牙
                            initBle();
                        } else {
                            finish();
                        }
                    }
                });
    }

    private void initBle() {
        Ble.Options options = new Ble.Options();
        options.logBleExceptions = true;//设置是否输出打印蓝牙日志
        options.throwBleException = true;//设置是否抛出蓝牙异常
        options.autoConnect = false;//设置是否自动连接
        options.scanPeriod = 12 * 1000;//设置扫描时长
        options.connectTimeout = 10 * 1000;//设置连接超时时长
        options.uuid_service = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");//设置主服务的uuid
        options.uuid_write_cha = UUID.fromString("0000ffe2-0000-1000-8000-00805f9b34fb");//设置可写特征的uuid
        options.uuid_read_cha = UUID.fromString("0000ffe3-0000-1000-8000-00805f9b34fb");//设置可读特征的uuid
        options.uuid_notify = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");//设置通知特征的uuid
        mBle.init(getApplicationContext(), options);
        //开始扫描
        mBle.startScan(scanCallback);
    }

    //扫描的回调
    BleScanCallback<BleDevice> scanCallback = new BleScanCallback<BleDevice>() {
        @Override
        public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) {
            synchronized (mBle.getLocker()) {
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
            }

        }

        @Override
        public void onStop() {
            super.onStop();
            Log.e(TAG, "onStop: ");
        }
    };

    /*连接的回调*/
    private BleConnCallback<BleDevice> connectCallback = new BleConnCallback<BleDevice>() {
        @Override
        public void onConnectionChanged(final BleDevice device) {
            if (device.isConnected()) {
                /*连接成功后，设置通知*/
            }
            Log.e(TAG, "onConnectionChanged: " + device.isConnected());
            mLeDeviceListAdapter.notifyDataSetChanged();
        }

        @Override
        public void onConnectException(BleDevice device, int errorCode) {
            super.onConnectException(device, errorCode);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == Ble.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        } else {
            //请求权限
            requestPermission();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
